package com.xbongbong.saas.service.impl;

import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CloneUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.marketManage.pojo.dto.MarketActivityUserDeleteBatchDTO;
import com.xbongbong.pro.marketManage.pojo.vo.MarketActivityUserDeleteBatchVO;
import com.xbongbong.saas.domain.entity.MarketActivityUserEntity;
import com.xbongbong.saas.model.MarketActivityUserModel;
import com.xbongbong.saas.service.MarketActivityUserService;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author chunyang.qin
 * @version v1.0
 * @date 2020/11/14 19:06
 * @since v1.0
 */
@Service("marketActivityUserService")

public class MarketActivityUserServiceImpl implements MarketActivityUserService {
    private static final Logger LOG = LoggerFactory.getLogger(MarketActivityUserServiceImpl.class);

    @Resource
    private MarketActivityUserModel marketActivityUserModel;
    @Resource
    private UserModel userModel;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public MarketActivityUserDeleteBatchVO deleteBatch(MarketActivityUserDeleteBatchDTO marketActivityUserDeleteBatchDTO) throws XbbException {
        MarketActivityUserDeleteBatchVO marketActivityUserDeleteBatchVO = new MarketActivityUserDeleteBatchVO();
        try {
            Map<String, Object> param = BeanUtil.convertBean2Map(marketActivityUserDeleteBatchDTO, true);
            List<MarketActivityUserEntity> marketActivityUserList = marketActivityUserModel.findEntitys(param);
            if (Objects.isNull(marketActivityUserList)) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            if (marketActivityUserList.isEmpty()) {
                return marketActivityUserDeleteBatchVO;
            }
            String corpid = marketActivityUserDeleteBatchDTO.getCorpid();
            if (!marketActivityUserList.isEmpty()) {
                List<MarketActivityUserEntity> updateCustomerUserList = new ArrayList<>();
                for (MarketActivityUserEntity item : marketActivityUserList) {
                    MarketActivityUserEntity marketActivityUserEntity = new MarketActivityUserEntity();
                    marketActivityUserEntity.setId(item.getId());
                    marketActivityUserEntity.setDataId(item.getDataId());
                    marketActivityUserEntity.setCorpid(corpid);
                    marketActivityUserEntity.setDel(-1);
                    long now = DateUtil.getInt();
                    marketActivityUserEntity.setUpdateTime(now);
                    updateCustomerUserList.add(marketActivityUserEntity);
                }
                if (!updateCustomerUserList.isEmpty()) {
                    marketActivityUserModel.updateBatch(updateCustomerUserList, corpid);
                }
            }
        } catch (Exception e) {
            LOG.error("MarketActivityUserServiceImpl.deleteBatch 执行出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return marketActivityUserDeleteBatchVO;
    }

    @Override
    public List<UserEntity> getMainUserList(List<Long> marketActivityIds, String corpid, Integer isMain) {

        if (marketActivityIds == null || marketActivityIds.isEmpty()) {
            return new ArrayList<>();
        }

        List<UserEntity> list = new ArrayList<>();
        Map<String,Object> param = new HashMap<>();
        param.put("dataIdIn", marketActivityIds);
        param.put("corpid", corpid);
        if (isMain != null) {
            param.put("isMain", isMain);
        }
        param.put("del", 0);
        param.put("orderByStr", "is_main desc");
        List<MarketActivityUserEntity> marketActivityUserList = marketActivityUserModel.findEntitys(param);

        List<String> userIdIn = new ArrayList<>();
        for(MarketActivityUserEntity marketActivityUser : marketActivityUserList){
            userIdIn.add(marketActivityUser.getUserId());
        }
        userIdIn.add("-1");
        param.clear();
        param.put("userIdIn", userIdIn);
        param.put("corpid", corpid);
        param.put("del", 0);
        List<UserEntity> userList = userModel.findEntitys(param);

        Map<String, UserEntity> userMap = new HashMap<>();
        for(UserEntity user : userList){
            userMap.put(user.getUserId(), user);
        }

        for(MarketActivityUserEntity marketActivityUser : marketActivityUserList){
            if(userMap.containsKey(marketActivityUser.getUserId())){
                UserEntity userEntity = (UserEntity) CloneUtil.deepClone(userMap.get(marketActivityUser.getUserId()));
                userEntity.setIsMain(marketActivityUser.getIsMain());
                list.add(userEntity);
            }
        }
        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void dataConsistencyUpdateUser(String corpid, String userId, String userName, String userAvatar) throws XbbException {
        try {
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("corpid", corpid);
            param.put("userId", userId);
            param.put("del", 0);
            List<MarketActivityUserEntity> customerUserEntityList = marketActivityUserModel.findEntitys(param);
            for (MarketActivityUserEntity entity : customerUserEntityList) {
                entity.setUserName(userName);
                entity.setUserAvatar(userAvatar);
                marketActivityUserModel.update(entity);
            }
        } catch (Exception e) {
            LOG.error("MarketActivityUserServiceImpl.dataConsistencyUpdateUser 出错，corpid=" + corpid + " userId=" + userId + "  userName=" + userName + "  userAvatar=" + userAvatar, e);
        }
    }
}
